;@+leo-ver=5-thin
;@+node:caminhante.20211214151146.6: * @file primitives.asm
;@@nocolor
;@@language assembly_x86
;@@tabwidth -2
;@+others
;@-others
;; TODO

  ;; Return and Data Stack's pointer control

PUSHRST:  dd _enter_native
  lea ebp, [ebp-4]
  pop eax
  mov [ebp], eax
  jmp _next_routine

POPRST:   dd _enter_native
  push dword [ebp]
  lea ebp, [ebp+4]
  jmp _next_routine

RSTFETCH: dd _enter_native
  push ebp
  jmp _next_routine

RSTSTORE: dd _enter_native
  pop ebp
  jmp _next_routine

RSTDROP:  dd _enter_native
  lea ebp, [ebp+4]
  jmp _next_routine

DSTFETCH: dd _enter_native
  mov eax, esp
  push eax
  jmp _next_routine

DSTSTORE: dd _enter_native
  pop esp
  jmp _next_routine

  ;; Input/Output

KEY:    dd _enter_native
  call _KEY
  push eax
  jmp _next_routine
_KEY:
  save_reg ebx,ecx,edx
.start:
  movzx ebx, [read.cursor]
  movzx ecx, [read.top]
  cmp ebx, ecx
  jge .read_more
  movzx eax, byte [read.buffer+ebx]
  inc [read.cursor]
  restore_reg ebx,ecx,edx
  ret
.read_more:
  mov eax, sys_read
  mov ebx, STDIN
  mov ecx, read.buffer
  mov edx, 4096
  int 80h
  test eax, eax
  jbe .read_error
  mov [read.top], ax
  mov [read.cursor], 0
  jmp _KEY.start
.read_error:
  mov eax, -1
  restore_reg ebx,ecx,edx
  ret

EMIT:   dd _enter_native
  pop eax
  call _EMIT
  jmp _next_routine
_EMIT:
  save_reg ebx,ecx,edx
  push eax
  mov ebx, STDOUT
  mov ecx, esp
  mov edx, 1
  mov eax, sys_write
  int 80h
  pop eax
  restore_reg ebx,ecx,edx
  ret

WORD1:  dd _enter_native
  call _WORD
  push word_buffer
  push ecx
  jmp _next_routine
_WORD:
  save_reg edi,eax
.start:
  mov edi, word_buffer
  mov ecx, 31
.read_first:
  call _KEY
  cmp eax, -1
  je .error
  cmp al, '\'
  je .skip_comment
  cmp al, ' '
  je .read_first
  cmp al, 10
  je .read_first
  stosb
.read_next:
  call _KEY
  cmp eax, -1
  je .error
  cmp al, '\'
  je .skip_comment
  cmp al, ' '
  je .end
  cmp al, 10
  je .end
  stosb
  loop .read_next
.end:
  neg ecx
  add ecx, 32
  restore_reg edi,eax
  ret
.error:
  mov ecx, -1
  restore_reg edi,eax
  ret
.skip_comment:
  call _KEY
  cmp eax, -1
  je .error
  cmp al, 10
  jne .skip_comment
  jmp .end

WRITE1:  dd _enter_native
  save_reg eax,ebx,ecx,edx
  pop edx ecx
  test edx, edx
  js @f
  jz @f
  mov ebx, STDOUT
  mov eax, sys_write
  int 80h
  @@:
  restore_reg eax,ebx,ecx,edx
  jmp _next_routine
;@-leo
